<template>
  <div class="write-off background" :style="{height: `${screenHeight}px`}">
    <div v-if="!showRecords">
      <div class="write-off-name">
        <span class="write-off-name-left">{{hxUser.userName}},欢迎您~</span>
        <span class="write-off-name-right" @click="loginout"><img src="@/assets/img/hx/out@2x.png">退出登录</span>
      </div>
      <div>
        <div class="write-off-content">
          选择核销方式
          <div class="write-off-content-query" @click="blur">
            <input ref="sm" v-model="code" placeholder="输入数字码" type="text"><span @click="getQuery">查询</span>
          </div>
          <div class="write-off-content-img">
            <img  id="sweepCode" src="@/assets/img/hx/sm@2x.png">
            <p>扫码核销</p>
          </div>
        </div>
         <div  class="write-off-records">
            <mt-cell title="核销记录" is-link :to="{name:'write-offRecords'}"></mt-cell>
        </div>
      </div>
    </div>
    <writeoffConfirm v-else :codeInfo="codeInfos"></writeoffConfirm>
  </div>
</template>

<script>
import wx from 'weixin-jsapi'
import writeoffConfirm from './write-offConfirm.vue'
import { wxconfig,codeInfo } from '@/api/request.js';
import { appid,globalUrl } from '@/assets/js/const.js';
import { setStore, getStore, removeStore } from '@/assets/js/utils.js';
import { Cell } from 'mint-ui';

export default {
  name: 'write-off',
  data() {
    return {
      showRecords:false,
      codeInfos:{},
      hxUser:{},
      code:''

    }
  },
  computed: {
      screenHeight () {
        return window.innerHeight;
      }
  },
  created(){
    let userId = getStore('userId');
    if(!userId){
      //跳转登录
      var fhUrl = window.location.href;
      setStore('fhUrl', fhUrl);
      this.$router.push('/wxLogin')
    }
    let hxUser = getStore('hxUser');
    if(hxUser && hxUser.id){
      this.hxUser = hxUser;
      this._wxconfig();
    }else{
      this.$router.push('/login')
    }
  },
  mounted() {
    this.$store.commit('UPDATE_PAGE_TITLE', '核销页');
    this.$store.commit('UPDATE_HEAD', false);
    this.$store.commit('UPDATE_FOOTER', false);
  },
  methods: {
    //查询
    getQuery(){
      let that = this;
      if(!this.code){
        this.$Toast('请输入或扫描核销码')
      }else{
        codeInfo(this.code).then(res => {
          if (res.code == 1) {
            if(res.data.registration){
              that.codeInfos={
                "title":res.data.registration.title || '',
                "nickName":res.data.registrationUser.nickName || '',
                "createTime":res.data.registration.createTime || '',
                "cost":res.data.registration.cost || '',
                "state":res.data.state || '',
                "code":res.data.code || '',
              }
              that.showRecords = true;
            }else{
              this.$Toast('未查到活动信息')
            }
          }else{
            this.$Toast(res.msg)
          }
        }).catch(err => console.log(err))
      }
    },
    //退出
    loginout(){
      removeStore('hxUser')
      this.$router.push('/login')
    },
    blur(){
        this.$refs.sm.focus();
    },
    //调扫码
    _wxconfig(){
      let that = this;
      wxconfig(globalUrl+'/hx').then(res => {
        if (res.code == 1) {
          let data = res.data
            wx.config({
            debug: false, // 开启调试模式
            appId: appid, // 必填，公众号的唯一标识
            timestamp: data.timestamp, // 必填，生成签名的时间戳
            nonceStr: data.nonceStr, // 必填，生成签名的随机串
            signature: data.signature,// 必填，签名，见附录1
            jsApiList: [
                          'checkJsApi',
                          'startRecord',
                          'stopRecord',
                          'scanQRCode',// 微信扫一扫接口
                          'translateVoice',
                          'openCard'
                        ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2 
          }); 
          wx.error(function(res) {
              alert("出错了：" + res.errMsg);//这个地方的好处就是wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
          });
          wx.ready(function() {
              wx.checkJsApi({
                    jsApiList : ['scanQRCode'],
                    success : function(res) {
                      console.log('scanQRCode',res)
                    }
              });
          });
           //点击按钮扫描二维码
           var sweepCode = document.getElementById("sweepCode");
            sweepCode.onclick = function(){
                wx.scanQRCode({
                    needResult : 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                    scanType : [ "qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
                    success : function(res) {
                      console.log('扫描返回的结果',res)
                        var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                        if(result){
                          that.code = result;
                          that.getQuery();
                        }
                    },
                    error : function(){
                        console.log('失败');
                    }
                });
            };
        }
      }).catch(err => console.log(err)) 
    }
  },
  components: {
    "mt-cell":Cell,
    writeoffConfirm
  }
}
</script>
<style scoped lang="scss">
.write-off{
    &-name{
      background-color: white;
      overflow: auto;
      padding: 10px;
      line-height: 30px;
      &-left{
        float:left;
        color:#FEBF00;
      }
      &-right{
        float:right;
        img{
          width:20px;
          margin-right: 5px;
          position: relative;
          top:4px;
        }
      }
    }
    &-content{
      text-align: left;
      border-radius: 5px;
      margin: 10px;
      background-color: white;
      padding: 10px;
      &-query{
        margin-top: 5px;
        border: 1px solid #ccc;
        padding:5px 0px 5px 5px;
        overflow: auto;
        box-shadow: -1px -1px 1px #ddd;
        input{
          height: 30px;
          line-height: 30px;
          margin-top: 3px;
          width:70%;
          float: left;
          font-size: 18px;
          border: none;
          outline:0;
        }
        span{
          font-size: 18px;
          float: right;
          border-left: 1px solid #ccc;
          padding: 5px 20px;
          color:#FEBF00;

        }
      }
      &-img{
          text-align: center;
          margin: 10px auto;
          img{
            width:60%;
            padding: 5px;
          }
      }
    }
    &-records{
      border-radius: 5px;
      margin: 10px;
      background-color: white;
      text-align: left;
    }
    
}
</style>
